import styled from 'styled-components';
import WebApp from '@twa-dev/sdk';
import './react-i18next-config'
import { useTranslation } from 'react-i18next';
import { Router, Routers } from './router';
import { useEffect, useMemo } from 'react';
import { disableSwipdown, getCookie, resetWindowPosition } from './utils/common';
import { useDispatch } from 'react-redux';
import { update } from './reducer/safeAreaReducer';
import Message from './component/Message';
import { isDev, isIOS, isTest, setIsFromMobile } from './utils/check';
import gtag from './google/analytics'
import { GtagEvent } from './google/analytics/Event';
import { logout } from './utils/user';
import './utils/error'
import Provider from './component/TonConnectUIProvider';
import { useTonConnectUI } from '@tonconnect/ui-react';
import { Adaptation } from './utils/adaptation';
import SwitchConfig from './utils/switch';

try {
  if (isDev()) {
    // eslint-disable-next-line @typescript-eslint/no-var-requires
    const VConsole = require('vconsole');
    new VConsole();
  }
} catch (error) {
  // temp
}


const Container = styled.div`
  text-align: center;
  position: relative;
`
const Header = styled.header`
  min-height: 100vh;
  /* display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center; */
  font-size: calc(10px + 2vmin);
  color: white;
  max-height: 100%;
  background-color: ${(prop) => prop.theme.background.normal};
`

// fix iOS Safari Modal background color 
const ModalBox = styled.div`
  .ant-modal-content {
      background-color: transparent !important;
      box-shadow: none !important;
  }
  .ant-modal-confirm-paragraph {
        max-width: 100%;
  }
  .ant-modal-header {
    background-color: transparent;
  }
`

const TonConnect = () => {
  const { t } = useTranslation()
  const [tonConnectUI] = useTonConnectUI();
  useEffect(() => {
    tonConnectUI.onStatusChange((wallet) => {
      if (wallet) {
        gtag.event(GtagEvent.ConnectWallet, { wallet: wallet.connectItems?.tonProof?.name || '' })
        return
      }
    }, (error) => {
      let msg = ''
      try {
        msg = error.message || t('ton.connectError')
        if ('info' in error) {
          const proto = Object.getPrototypeOf(error)
          if ('info' in proto && proto.info) {
            msg = proto.info
          }
        }
      } catch (error) {
        // tmp
      }
      Message.error(msg)
      tonConnectUI.closeModal()
    })

    tonConnectUI.onModalStateChange((state) => {
      if (state.status === 'closed' && isIOS()) {
        resetWindowPosition()
      }
    })
  }, [t, tonConnectUI])
  return <></>
}

function App() {
  gtag.event(GtagEvent.Load)
  const { t } = useTranslation()
  const dispatch = useDispatch()
  useEffect(() => {
    WebApp.ready();
    WebApp.enableClosingConfirmation();
    const safeAreaStr = getCookie('safeArea');
    let safeArea: { [key: string]: number | string } = {};
    try {
      const json = JSON.parse(safeAreaStr);
      if (typeof json === 'object') {
        safeArea = json
        setIsFromMobile(true);
      } else {
        console.debug('safeArea', json);
      }
    } catch (_) {
      // empty
    }

    const defaultTop = WebApp.initData ? 0 : 24;
    const top = safeArea['top'] || defaultTop;
    const data = {
      left: `${safeArea['left'] || 0}px`,
      right: `${safeArea['right'] || 0}px`,
      top: `${top}px`,
      bottom: `${safeArea['bottom'] || 24}px`,
    }

    Message.config({ top: Number(top) + 10 })
    dispatch(update(data))
  }, [dispatch])

  useEffect(() => {
    disableSwipdown()
    SwitchConfig.init()
  }, [])

  useEffect(() => {
    // mini app setting
    if (!WebApp.isExpanded) {
      WebApp.expand()
    }

    let func: () => void;
    if (isDev() || isTest()) {
      const settings = WebApp.SettingsButton.show();
      const onSettingClick = () => {
        Message.info('logout')
        logout();
      }
      settings.onClick(onSettingClick)
      func = () => {
        settings.offClick(onSettingClick)
      }
    }

    const change = () => {
      if (!WebApp.isExpanded) {
        WebApp.expand();
      }
    }
    WebApp.onEvent('viewportChanged', change)
    const adaptation = new Adaptation()
    adaptation.addKeyBoardEventListener()

    return () => {
      adaptation.removeKeyBoardEventListener()
      WebApp.offEvent('viewportChanged', change)
      func?.()
    }
  }, [])

  const tabbars = useMemo(() => {
    return [
      { path: Router.Home, name: t('tabbar.home'), icon: { normal: 'tab_home_normal', active: 'tab_home_active' } },
      { path: Router.Team, name: t('tabbar.team'), icon: { normal: 'tab_team_normal', active: 'tab_team_active' } },
      { path: Router.Accelerate, icon: { normal: 'tab_rocket_normal', active: 'tab_rocket_active' } },
      { path: Router.Task, name: t('tabbar.task'), icon: { normal: 'tab_task_normal', active: 'tab_task_active' } },
      { path: Router.Wallet, name: t('tabbar.wallet'), icon: { normal: 'tab_wallet_normal', active: 'tab_wallet_active' } }
    ]
  }, [t])


  return (
    <Provider>
      <Container>
        <Header>
          <Routers
            tabbar={tabbars}
          />
        </Header>
      </Container>
      <TonConnect />
      <ModalBox id="ele_modal"></ModalBox>
    </Provider>
  );
}

export default App;
